package com.xbjtech.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MapUtil {

	public static String getHttpResponse(String allConfigUrl) {
		BufferedReader in = null;
		StringBuffer result = null;
		try {
			URI uri = new URI(allConfigUrl);
			URL url = uri.toURL();
			URLConnection connection = url.openConnection();
			connection.setRequestProperty("Content-type", "text/html");
			connection.setRequestProperty("Accept-Charset", "utf-8");
			connection.setRequestProperty("contentType", "utf-8");
			connection.connect();
			result = new StringBuffer();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return null;
	}

	public static String distance(String origins, String destination) {
		String url="http://restapi.amap.com/v3/distance?origins="+origins+"&destination="+destination+"&output=json&key=a69c1dbb9caa26bb39565eb189a0ece7";
		System.out.println(getHttpResponse(url));
		ObjectMapper mapper = new ObjectMapper();
		String distance=null;
		try {
			JsonNode node = mapper.readTree(getHttpResponse(url));
			distance = node.get("results").get(0).get("distance").toString();
			System.out.println(distance);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return distance;
	}

	public static String coordinate(String address) {
		try {  
            address = URLEncoder.encode(address, "utf-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
		String url="http://restapi.amap.com/v3/geocode/geo?address="+address+"&output=json&key=a69c1dbb9caa26bb39565eb189a0ece7";
		ObjectMapper mapper=new ObjectMapper();
		String coordinateString=null;
		try {
			JsonNode node = mapper.readTree(getHttpResponse(url));
			node = node.get("geocodes");
			coordinateString=node.get(0).get("location").toString();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(coordinateString);
		return coordinateString;
	}
	
	@Test
	public void coordinateTest() {
		distance("116.481028,39.989643", "117.233703,31.814841");
		coordinate("安徽省合肥市政务区新城国际");
	}
}







